package com.hzhr.iot.cqgas.ds.controller;

import com.hzhr.iot.core.constant.CommonOptions;
import com.hzhr.iot.core.util.HzhrDateUtil;
import com.hzhr.iot.core.util.HzhrTypeUtil;
import com.hzhr.iot.cqgas.ds.dao.device.custom.DeviceDao;
import com.hzhr.iot.cqgas.ds.dao.device.example.DevCollectDeviceDao;
import com.hzhr.iot.cqgas.ds.dao.device.example.DevCollectDeviceTypeDao;
import com.hzhr.iot.cqgas.ds.dao.device.example.DevIotDeviceDao;
import com.hzhr.iot.cqgas.ds.dao.smartmeter.custom.SmDao;
import com.hzhr.iot.cqgas.ds.dao.toll.custom.TollGasUserCustomDao;
import com.hzhr.iot.cqgas.ds.dao.toll.example.TollGasUserDao;
import com.hzhr.iot.cqgas.ds.dao.user.custom.UserCustomDao;
import com.hzhr.iot.cqgas.ds.entity.device.*;
import com.hzhr.iot.cqgas.ds.entity.smartmeter.NbMeterEntity;
import com.hzhr.iot.cqgas.ds.entity.toll.TollGasUserEntity;
import com.hzhr.iot.cqgas.ds.entity.toll.TollGasUserExample;
import com.hzhr.iot.cqgas.ds.service.TollOptionsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class NbMeterController {
    @Autowired
    DevCollectDeviceDao devCollectDeviceDao;
    @Autowired
    DeviceDao deviceDao;
    @Autowired
    SmDao smDao;
    @Autowired
    UserCustomDao userCustomDao;
    @Autowired
    TollGasUserCustomDao tollGasUserCustomDao;
    @Autowired
    TollGasUserDao tollGasUserDao;
    @Autowired
    TollOptionsService tollOptionsService;
    @Autowired
    DevCollectDeviceTypeDao devCollectDeviceTypeDao;
    @Autowired
    DevIotDeviceDao devIotDeviceDao;

    private Logger logger = LoggerFactory.getLogger(NbMeterController.class);

    @Value("${companyId}")
    String companyId;

    @RequestMapping(value = "/syncNbMeter")
    public void syncNbMeter() {
        int addCount = 0;
        int updateCount = 0;
        long startTime = new Date().getTime();

        String resident = tollOptionsService.getCode("GAS_USER_TYPE", "RESIDENTIAL_USER");
        String commercial = tollOptionsService.getCode("GAS_USER_TYPE", "COMMERCIAL_USER");

        //查询出采集设备类型
        List<DevCollectDeviceTypeEntity> devCollectDeviceTypeEntities = devCollectDeviceTypeDao.selectByExample(null);
        Map<String, Integer> collectDeviceTypes = new HashMap<>();
        for (DevCollectDeviceTypeEntity devCollectDeviceTypeEntity :
                devCollectDeviceTypeEntities) {
            collectDeviceTypes.put(devCollectDeviceTypeEntity.getOutId(), devCollectDeviceTypeEntity.getId());
        }

        int i = 0;
        while (true) {
            Integer count = 5000;
            Integer start =  i * count;

            //查询平台自建的nb表的代码
            List<Map<String, Object>> iotDevices = deviceDao.select16(start, count);
            for (Map<String, Object> iotDevice :
                    iotDevices) {
                String code = HzhrTypeUtil.object2string(iotDevice.get("CODE"));
                Integer id = HzhrTypeUtil.object2integer(iotDevice.get("ID"));

                try {
                    //根据平台自建的nb表的代码找到这些表的营销系统信息
                    NbMeterEntity nbMeter = smDao.select4(code);
                    if (nbMeter != null) {
                        String ORG_ID = nbMeter.getOrgId();
                        String YQDZ_YQZH = nbMeter.getYqdzYqzh();
                        String YQDZ_HZ_MC = nbMeter.getYqdzHzMc();
                        String YQDZ_SM = nbMeter.getYqdzSm();
                        String yqdzKhLx = nbMeter.getYqdzKhLx();
                        String mtId = nbMeter.getMtId();
                        String mtModel = nbMeter.getMtModel();
                        String rqbKssyrq = nbMeter.getRqbKssyrq();


                        //根据orgId找到部门
                        String deptCode = ORG_ID.replaceFirst("0000", "9-01");
                        Map<String, Object> dept = userCustomDao.select7(deptCode);
                        if (dept == null) continue;

                        //根据yqdzYqzh找到燃气用户编号，如果过找不到燃气用户则自建燃气用户

                        Integer gasUserId = tollGasUserCustomDao.select3(YQDZ_YQZH);
                        if (gasUserId == null) {
                            TollGasUserEntity tollGasUserEntity = new TollGasUserEntity();
                            tollGasUserEntity.setCode(YQDZ_YQZH);
                            tollGasUserEntity.setName(YQDZ_HZ_MC != null ? YQDZ_HZ_MC : "未知");
                            tollGasUserEntity.setAddress(YQDZ_SM);
                            if ("1".equals(yqdzKhLx)) {
                                tollGasUserEntity.setTypeCode(commercial);
                            } else if ("2".equals(yqdzKhLx)) {
                                tollGasUserEntity.setTypeCode(resident);
                            } else {
                                tollGasUserEntity.setTypeCode("0");
                            }
                            tollGasUserEntity.setCompanyId(Integer.parseInt(companyId));
                            tollGasUserEntity.setDeptId(HzhrTypeUtil.object2integer(dept.get("ID")));
                            tollGasUserEntity.setCreateTime(new Date());
                            tollGasUserEntity.setCreateUserId(0);
                            tollGasUserEntity.setResourceCode(HzhrTypeUtil.object2string(dept.get("RESOURCE_CODE")));
                            tollGasUserEntity.setIsValid(CommonOptions.YES_NO.YES);
                            tollGasUserEntity.setState("1");
                            tollGasUserDao.insert(tollGasUserEntity);

                            gasUserId = tollGasUserEntity.getId();
                        } else {
                            TollGasUserEntity tollGasUserEntity = new TollGasUserEntity();
                            tollGasUserEntity.setCode(YQDZ_YQZH);
                            tollGasUserEntity.setName(YQDZ_HZ_MC != null ? YQDZ_HZ_MC : "未知");
                            tollGasUserEntity.setAddress(YQDZ_SM);
                            if ("1".equals(yqdzKhLx)) {
                                tollGasUserEntity.setTypeCode(commercial);
                            } else if ("2".equals(yqdzKhLx)) {
                                tollGasUserEntity.setTypeCode(resident);
                            } else {
                                tollGasUserEntity.setTypeCode("0");
                            }
                            tollGasUserEntity.setCompanyId(Integer.parseInt(companyId));
                            tollGasUserEntity.setDeptId(HzhrTypeUtil.object2integer(dept.get("ID")));
                            tollGasUserEntity.setUpdateTime(new Date());
                            tollGasUserEntity.setUpdateUserId(0);
                            tollGasUserEntity.setResourceCode(HzhrTypeUtil.object2string(dept.get("RESOURCE_CODE")));

                            TollGasUserExample tollGasUserExample = new TollGasUserExample();
                            tollGasUserExample.createCriteria().andIdEqualTo(gasUserId);
                            tollGasUserDao.updateByExampleSelective(tollGasUserEntity, tollGasUserExample);
                        }

                        //根据营销系统信息创建或更新nb表的采集设备台账
                        DevCollectDeviceExample devCollectDeviceExample = new DevCollectDeviceExample();
                        devCollectDeviceExample.createCriteria().andCodeEqualTo(code).andCategoryCodeEqualTo("1").andIsValidEqualTo("1");
                        List<DevCollectDeviceEntity> collectDevices = devCollectDeviceDao.selectByExample(devCollectDeviceExample);
                        if (collectDevices.size() > 0) {
                            DevCollectDeviceEntity devCollectDeviceEntity = collectDevices.get(0);

                            Integer typeId = collectDeviceTypes.get(mtId);
                            if (typeId != null) {
                                devCollectDeviceEntity.setTypeId(typeId);
                            } else {
                                devCollectDeviceEntity.setTypeId(0);
                            }

                            devCollectDeviceEntity.setDes(mtModel);
                            devCollectDeviceEntity.setIotDeviceId(id);

                            devCollectDeviceEntity.setCompanyId(9);
                            devCollectDeviceEntity.setDeptId(HzhrTypeUtil.object2integer(dept.get("ID")));
                            devCollectDeviceEntity.setDeptCode(deptCode);
                            devCollectDeviceEntity.setResourceCode(HzhrTypeUtil.object2string(dept.get("RESOURCE_CODE")));
                            devCollectDeviceEntity.setGasUserId(gasUserId);
                            devCollectDeviceEntity.setGasUserName(YQDZ_HZ_MC);
                            devCollectDeviceEntity.setGasUserCode(YQDZ_YQZH);
                            devCollectDeviceEntity.setGasUserAddress(YQDZ_SM);
                            devCollectDeviceEntity.setInstallAddress(YQDZ_SM);
                            devCollectDeviceEntity.setUpdateUserId(0);
                            devCollectDeviceEntity.setUpdateTime(new Date());
                            devCollectDeviceDao.updateByPrimaryKey(devCollectDeviceEntity);
                            updateCount++;
                        } else {
                            DevCollectDeviceEntity devCollectDeviceEntity = new DevCollectDeviceEntity();
                            devCollectDeviceEntity.setCode(code);
                            devCollectDeviceEntity.setCategoryCode("1");

                            Integer typeId = collectDeviceTypes.get(mtId);
                            if (typeId != null) {
                                devCollectDeviceEntity.setTypeId(typeId);
                            } else {
                                devCollectDeviceEntity.setTypeId(0);
                            }

                            devCollectDeviceEntity.setDes(mtModel);
                            devCollectDeviceEntity.setIotDeviceId(id);
                            devCollectDeviceEntity.setCompanyId(9);
                            devCollectDeviceEntity.setDeptId(HzhrTypeUtil.object2integer(dept.get("ID")));
                            devCollectDeviceEntity.setDeptCode(deptCode);
                            devCollectDeviceEntity.setResourceCode(HzhrTypeUtil.object2string(dept.get("RESOURCE_CODE")));
                            devCollectDeviceEntity.setGasUserId(gasUserId);
                            devCollectDeviceEntity.setGasUserName(YQDZ_HZ_MC);
                            devCollectDeviceEntity.setGasUserCode(YQDZ_YQZH);
                            devCollectDeviceEntity.setGasUserAddress(YQDZ_SM);
                            devCollectDeviceEntity.setInstallAddress(YQDZ_SM);
                            devCollectDeviceEntity.setCreateUserId(0);
                            devCollectDeviceEntity.setCreateTime(new Date());
                            if (!StringUtils.isEmpty(rqbKssyrq)) {
                                devCollectDeviceEntity.setInstallTime(HzhrDateUtil.strToDate(rqbKssyrq));
                            }
                            devCollectDeviceEntity.setIsValid("1");
                            devCollectDeviceEntity.setState("1");
                            devCollectDeviceDao.insert(devCollectDeviceEntity);

                            addCount++;
                        }


                    }
                } catch (Throwable e) {
                    logger.error("同步nb表信息异常", e);
                }
            }

            if (iotDevices.size() < 5000) {
                break;
            }

            i++;
        }

        long endTime = new Date().getTime();
        logger.info("更新自建nb表信息结束: " + (endTime - startTime) / 1000 + "s");
        logger.info("同步时间: " + (endTime - startTime) / 1000 + "s");
        logger.info("更新数量: " + updateCount + "条");
        logger.info("新增数量: " + addCount + "条");

    }
}
